import { useCallback, useEffect, useState } from 'react';
import type { Context } from '../context/Context';
import type { TypedKey } from '../context/types';

/**
 * 为指定的 Context 实例创建专用的 useListen Hook
 * @param context 上下文实例
 * @returns 返回一个类型安全的 useListen Hook
 */
export function createUseListen<TContext extends Context>(context: TContext) {
  return function useListen<T>(
    key: TypedKey<T>,
  ): [T, (value: T | ((prev: T) => T)) => void] {
    const [value, setValue] = useState(() => context.getData(key));

    useEffect(() => {
      const unsubscribe = context.subscribe(key, (newValue: T) => {
        setValue(newValue);
      });
      return unsubscribe;
    }, [key, context.subscribe]);

    const set = useCallback(
      (newValue: T | ((prev: T) => T)) => {
        const finalValue =
          typeof newValue === 'function'
            ? (newValue as (prev: T) => T)(context.getData(key))
            : newValue;
        context.setData(key, finalValue);
      },
      [key, context.getData, context.setData],
    );

    return [value, set];
  };
}
